import React, { useState } from 'react';
import { Handle, Position } from '@xyflow/react';
import { Box, Typography, IconButton, Chip, Divider, Paper } from '@mui/material';
import { 
  PlayCircle as PlayCircleIcon,
  BarChart as BarChartIcon 
} from '@mui/icons-material';
import { NodeData, NODE_TYPES } from './NodeTypes';
import ModelVisualizationDialog from '../dialogs/ModelVisualizationDialog';

interface ModelEvaluationNodeProps {
  id: string;
  data: NodeData;
  selected: boolean;
}

// 模型评估节点组件
const ModelEvaluationNode: React.FC<ModelEvaluationNodeProps> = ({ id, data, selected }) => {
  // 添加对话框状态
  const [dialogOpen, setDialogOpen] = React.useState(false);
  // 添加测试数据状态
  const [testData, setTestData] = useState<{
    metrics?: any;
    feature_importance?: any;
  } | null>(null);

  // 根据可视化类型选择颜色
  const getVisualizationNodeColor = () => {
    switch (data.type) {
      case NODE_TYPES.MODEL_EVALUATION: return '#E91E63'; // 粉红色
      default: return '#9C27B0'; // 紫色
    }
  };

  const borderColor = getVisualizationNodeColor();
  const bgColor = selected ? `${borderColor}22` : '#fff';

  // 调试输出: 查看节点数据
  React.useEffect(() => {
    console.log(`ModelEvaluationNode ${id} 的数据:`, data);
    console.log(`ModelEvaluationNode ${id} 的执行结果:`, data.lastExecutionResult);
    if (data.lastExecutionResult?.metrics) {
      console.log(`ModelEvaluationNode ${id} 的metrics:`, data.lastExecutionResult.metrics);
    }
  }, [id, data]);

  // 获取模型评估指标（如果存在）
  const getMetrics = () => {
    if (data.lastExecutionResult?.metrics) {
      const metrics = data.lastExecutionResult.metrics;
      console.log(`节点 ${id} 获取到metrics:`, metrics);
      return metrics;
    }
    console.log(`节点 ${id} 没有metrics数据`);
    return null;
  };

  const metrics = getMetrics();

  // 获取特征重要性（如果存在）
  const getFeatureImportance = () => {
    if (data.lastExecutionResult?.feature_importance) {
      return data.lastExecutionResult.feature_importance;
    }
    return null;
  };

  // 格式化百分比数值
  const formatPercent = (value: number) => {
    return (value * 100).toFixed(2) + '%';
  };

  const hasMetrics = metrics && typeof metrics.accuracy === 'number' && 
                     typeof metrics.precision === 'number' && 
                     typeof metrics.recall === 'number' && 
                     typeof metrics.f1 === 'number';
  
  // 检查是否有可视化数据
  const hasVisualizationData = hasMetrics || 
    (data.lastExecutionResult?.feature_importance && 
     Object.keys(data.lastExecutionResult.feature_importance).length > 0);
  
  console.log(`节点 ${id} hasMetrics:`, hasMetrics);
  if (metrics) {
    console.log(`节点 ${id} metrics值类型:`, {
      accuracy: typeof metrics.accuracy,
      precision: typeof metrics.precision,
      recall: typeof metrics.recall,
      f1: typeof metrics.f1
    });
    
    // 更详细地检查ROC曲线数据
    const rocCurveData = metrics.roc_curve;
    console.log(`节点 ${id} ROC曲线原始数据:`, rocCurveData);
    console.log(`节点 ${id} 是否有ROC曲线数据:`, Boolean(rocCurveData));
    
    if (rocCurveData) {
      // 检查数组是否存在且不为空
      const hasFpr = Array.isArray(rocCurveData.fpr) && rocCurveData.fpr.length > 0;
      const hasTpr = Array.isArray(rocCurveData.tpr) && rocCurveData.tpr.length > 0;
      
      console.log(`节点 ${id} ROC曲线数据完整性:`, {
        hasFpr,
        hasTpr,
        fprLength: hasFpr ? rocCurveData.fpr.length : 0,
        tprLength: hasTpr ? rocCurveData.tpr.length : 0,
        auc: rocCurveData.auc
      });
      
      if (hasFpr && hasTpr) {
        // 显示前几个数据点，验证数据格式
        const firstFewPoints = rocCurveData.fpr.slice(0, 5).map((fpr: number, idx: number) => {
          return { fpr, tpr: rocCurveData.tpr[idx] };
        });
        console.log(`节点 ${id} ROC曲线前5个点:`, firstFewPoints);
      } else {
        console.warn(`节点 ${id} ROC曲线数据不完整或格式错误`);
      }
    }
  }
  
  // 检查特征重要性数据
  const featureImportance = data.lastExecutionResult?.feature_importance;
  console.log(`节点 ${id} 是否有特征重要性数据:`, Boolean(featureImportance));
  if (featureImportance) {
    console.log(`节点 ${id} 特征重要性数据:`, Object.keys(featureImportance).length, '个特征');
    console.log(`特征重要性前三项:`, Object.entries(featureImportance).slice(0, 3));
  }

  // 处理打开和关闭对话框
  const handleOpenDialog = (e: React.MouseEvent) => {
    e.stopPropagation();
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
    // 对话框关闭时清除测试数据
    if (testData) {
      setTestData(null);
    }
  };
  
  // 测试功能 - 仅用于开发测试，不会影响生产环境
  const testVisualizationData = (e: React.MouseEvent) => {
    if (e.altKey && e.ctrlKey) { // 只有同时按下Alt和Ctrl键时才激活测试功能
      e.stopPropagation();
      console.log("激活测试数据");
      
      // 创建模拟的ROC曲线数据
      const mockRocCurve = {
        fpr: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
        tpr: [0, 0.4, 0.5, 0.7, 0.8, 0.8, 0.85, 0.9, 0.95, 0.98, 1],
        thresholds: [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0],
        auc: 0.83
      };
      
      // 创建模拟的特征重要性数据
      const mockFeatureImportance = {
        "feature1": 0.35,
        "feature2": 0.25,
        "feature3": 0.15,
        "feature4": 0.12,
        "feature5": 0.08,
        "feature6": 0.05
      };
      
      // 创建模拟的混淆矩阵
      const mockConfusionMatrix = [
        [45, 5],
        [8, 42]
      ];
      
      // 创建模拟的评估数据
      const mockEvaluationData = {
        metrics: {
          accuracy: 0.87,
          precision: 0.89,
          recall: 0.84,
          f1: 0.86,
          confusion_matrix: mockConfusionMatrix,
          roc_curve: mockRocCurve
        },
        feature_importance: mockFeatureImportance
      };
      
      console.log("设置测试数据:", mockEvaluationData);
      
      // 设置测试数据并打开对话框
      setTestData(mockEvaluationData);
      setDialogOpen(true);
    }
  };
  
  // 确定使用的数据（优先使用测试数据）
  const visualizationMetrics = testData?.metrics || data.lastExecutionResult?.metrics;
  const visualizationFeatures = testData?.feature_importance || data.lastExecutionResult?.feature_importance;
  
  // 添加调试日志
  React.useEffect(() => {
    if (dialogOpen) {
      console.log('开启对话框时传递的数据:', {
        metrics: visualizationMetrics,
        feature_importance: visualizationFeatures
      });
      
      // 检查ROC曲线数据
      if (visualizationMetrics?.roc_curve) {
        console.log('ROC曲线数据检查:', {
          hasFpr: Array.isArray(visualizationMetrics.roc_curve.fpr),
          fprLength: Array.isArray(visualizationMetrics.roc_curve.fpr) ? visualizationMetrics.roc_curve.fpr.length : 0,
          hasTpr: Array.isArray(visualizationMetrics.roc_curve.tpr),
          tprLength: Array.isArray(visualizationMetrics.roc_curve.tpr) ? visualizationMetrics.roc_curve.tpr.length : 0,
          auc: visualizationMetrics.roc_curve.auc
        });
      }
      
      // 检查特征重要性数据
      if (visualizationFeatures) {
        console.log('特征重要性数据检查:', {
          hasData: !!visualizationFeatures,
          keysCount: Object.keys(visualizationFeatures).length,
          sampleKeys: Object.keys(visualizationFeatures).slice(0, 3)
        });
      }
    }
  }, [dialogOpen, visualizationMetrics, visualizationFeatures]);

  return (
    <Box
      sx={{
        padding: 1.5,
        borderRadius: 2,
        background: bgColor,
        minWidth: 180,
        textAlign: 'center',
        fontSize: '14px',
        color: '#333',
        border: `2px solid ${borderColor}`,
        boxShadow: selected
          ? `0 0 10px ${borderColor}66`
          : '0 2px 8px rgba(0,0,0,0.1)',
        transition: 'all 0.3s ease',
        '&:hover': {
          boxShadow: `0 0 15px ${borderColor}44`,
          transform: 'translateY(-2px)',
        },
        position: 'relative',
      }}
      onClick={testVisualizationData}
    >
      {/* 节点标题 */}
      <Typography
        component="div"
        sx={{
          fontWeight: 600,
          mb: 0.5,
          color: '#333',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {data.label || '模型评估'}
      </Typography>
      
      {/* 节点类型标签 */}
      <Typography
        variant="caption"
        component="div"
        sx={{
          opacity: 0.7,
          mb: 1,
          fontSize: '0.7rem',
        }}
      >
        {data.type?.replace(/_/g, ' ') || ''}
      </Typography>
      
      {/* 显示模型评估指标（如果存在） */}
      {hasMetrics ? (
        <Paper elevation={0} sx={{ p: 1, bgcolor: '#f5f5f5', borderRadius: 1, mt: 1 }}>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="caption" sx={{ fontWeight: 500 }}>准确率:</Typography>
              <Chip
                label={formatPercent(metrics.accuracy)}
                size="small"
                color="primary"
                variant="outlined"
                sx={{ fontSize: '0.65rem', height: 20 }}
              />
            </Box>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="caption" sx={{ fontWeight: 500 }}>精确率:</Typography>
              <Chip
                label={formatPercent(metrics.precision)}
                size="small"
                color="success"
                variant="outlined"
                sx={{ fontSize: '0.65rem', height: 20 }}
              />
            </Box>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="caption" sx={{ fontWeight: 500 }}>召回率:</Typography>
              <Chip
                label={formatPercent(metrics.recall)}
                size="small"
                color="secondary"
                variant="outlined"
                sx={{ fontSize: '0.65rem', height: 20 }}
              />
            </Box>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="caption" sx={{ fontWeight: 500 }}>F1分数:</Typography>
              <Chip
                label={formatPercent(metrics.f1)}
                size="small"
                color="info"
                variant="outlined"
                sx={{ fontSize: '0.65rem', height: 20 }}
              />
            </Box>
          </Box>
        </Paper>
      ) : (
        <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', mt: 1 }}>
          请连接到机器学习模型并执行<br/>以获取评估结果
        </Typography>
      )}
      
      {/* 执行图标 */}
      <IconButton
        size="small"
        sx={{
          position: 'absolute',
          top: -12,
          right: -12,
          backgroundColor: '#fff',
          border: `1px solid ${borderColor}`,
          '&:hover': {
            backgroundColor: '#f0f0f0',
            transform: 'scale(1.1)',
          },
          transition: 'all 0.2s ease',
          boxShadow: '0 2px 5px rgba(0,0,0,0.1)',
        }}
        onClick={(e) => {
          e.stopPropagation();
          const event = new CustomEvent('execute-node', { detail: { nodeId: id } });
          window.dispatchEvent(event);
        }}
      >
        <PlayCircleIcon fontSize="small" color="primary" />
      </IconButton>

      {/* 图表按钮 - 只有当有可视化数据时才显示 */}
      {hasVisualizationData && (
        <IconButton
          size="small"
          sx={{
            position: 'absolute',
            top: -12,
            right: 22, // 放在执行按钮旁边
            backgroundColor: '#fff',
            border: `1px solid ${borderColor}`,
            '&:hover': {
              backgroundColor: '#f0f0f0',
              transform: 'scale(1.1)',
            },
            transition: 'all 0.2s ease',
            boxShadow: '0 2px 5px rgba(0,0,0,0.1)',
          }}
          onClick={handleOpenDialog}
        >
          <BarChartIcon fontSize="small" color="secondary" />
        </IconButton>
      )}

      {/* 模型可视化对话框 */}
      <ModelVisualizationDialog
        open={dialogOpen}
        onClose={handleCloseDialog}
        nodeId={id}
        metrics={visualizationMetrics}
        feature_importance={visualizationFeatures}
      />

      {/* 输入端口 */}
      <Handle
        type="target"
        position={Position.Top}
        style={{
          background: borderColor,
          width: '10px',
          height: '10px',
          border: '2px solid #fff',
        }}
      />

      {/* 输出端口 */}
      <Handle
        type="source"
        position={Position.Bottom}
        style={{
          background: borderColor,
          width: '10px',
          height: '10px',
          border: '2px solid #fff',
        }}
      />
    </Box>
  );
};

export default ModelEvaluationNode; 